package com.wang.cloudstorage.db;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;

public class MongoDBClient implements DatabaseClient{
	static Logger logger = LoggerFactory.getLogger(MongoDBClient.class);
	
	DB db = null;
	public DB getDB()
	{
		return db;
	}

	protected String host;
	protected int port;
	protected String schema;
	protected String userName;
	protected String password;
	public String getSchema() {
		return schema;
	}
	public void setSchema(String schema) {
		this.schema = schema;
	}
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public void close(){;}
	public void Connect()
	{
		MongoClient mongoClient = null;
		try {
			mongoClient = new MongoClient(host, port);
		} catch (UnknownHostException e) {
			logger.error(e.getMessage() ,  e);
			throw new RuntimeException(e);
		}

		db = mongoClient.getDB(schema);
		if(null != userName && null != password)
		{
			if(!db.authenticate(userName, password.toCharArray()))
			{
				throw new RuntimeException("Authenticate failed.");
			}
		}
	}
	
	public void setCollection(String string) {
	}
	
	public void insert(Object bsonObject, String scope)
	{
		DBCollection table = db.getCollection(scope);
		table.insert((DBObject)bsonObject);
	}
	
	public void update(Object values, Object where, String scope) {
		DBCollection table = db.getCollection(scope);
		table.update((DBObject) where, (DBObject) values);
	}
	
	public List<JSONObject> select(Object searchQuery, String scope) throws JSONException {
		List<JSONObject> results = new ArrayList<JSONObject>();
		
		DBCollection table = db.getCollection(scope);
		
		DBCursor cursor = null;
		cursor = table.find((BasicDBObject)searchQuery);
		
		while(cursor.hasNext())
		{
			results.add(new JSONObject(JSON.serialize(cursor.next())));
		}
		cursor.close();

		return results;
	}
	
	public List<JSONObject> selectAll(String scope) throws JSONException
	{
		return select(null, scope);
	}
	
	public void delete(Object where, String scope)
	{
		DBCollection table = db.getCollection(scope);

		table.remove((DBObject) where);
	}
}
